#include "orangepch.h"
#include "OpenGlTexture.h"
#include "stb_image.h"



namespace Orange {
	OpenGlTexture2D::OpenGlTexture2D(const uint32_t& width, const uint32_t& height):m_Width(width), m_Height(height)
	{
		 m_InternalFormat = GL_RGBA8, m_Format = GL_RGBA;


		glCreateTextures(GL_TEXTURE_2D, 1, &m_RendererId);

		glTextureStorage2D(m_RendererId, 1, m_InternalFormat, m_Width, m_Height);

		glTextureParameteri(m_RendererId, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTextureParameteri(m_RendererId, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

		glTextureParameteri(m_RendererId, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTextureParameteri(m_RendererId, GL_TEXTURE_WRAP_T, GL_REPEAT);


	}
	OpenGlTexture2D::OpenGlTexture2D(const std::string& path):m_Path(path)
	{
	int width, height, channel;
	stbi_set_flip_vertically_on_load(true);
	 stbi_uc* data = stbi_load(path.c_str(), &width, &height, &channel,0);
	
	 ORANGE_CORE_ASSERT(data, "Failed to load Image!");

	 m_Width = width;
	 m_Height = height;


	 if (channel == 4) {
		 m_InternalFormat = GL_RGBA8, m_Format = GL_RGBA;
	 }
	 else if (channel == 3) {
		 m_InternalFormat = GL_RGB8, m_Format = GL_RGB;
	 }

	 ORANGE_CORE_ASSERT(m_InternalFormat & m_Format, "don't support this image!");

	 glCreateTextures(GL_TEXTURE_2D, 1, &m_RendererId);

	 glTextureStorage2D(m_RendererId, 1, m_InternalFormat, m_Width, m_Height);

	 glTextureParameteri(m_RendererId, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	 glTextureParameteri(m_RendererId, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

	 glTextureParameteri(m_RendererId, GL_TEXTURE_WRAP_S, GL_REPEAT);
	 glTextureParameteri(m_RendererId, GL_TEXTURE_WRAP_T, GL_REPEAT);

	 glTextureSubImage2D(m_RendererId, 0, 0, 0, m_Width, m_Height, m_Format, GL_UNSIGNED_BYTE, data);

	 // �ϴ�֮��ɾ��ͼƬ
	 stbi_image_free(data);
	}

	OpenGlTexture2D::~OpenGlTexture2D()
	{
		glDeleteTextures(1, &m_RendererId);
	}


	void OpenGlTexture2D::Bind(uint32_t sort){
		glBindTextureUnit(sort, m_RendererId);
	}
	void OpenGlTexture2D::SetData(void* data, uint32_t size)
	{
		uint32_t bpp = m_InternalFormat == GL_RGBA8 ? 4 : 3;
		ORANGE_CORE_ASSERT(size == m_Width * m_Height * bpp, "data must be entrie Image");
		glTextureSubImage2D(m_RendererId, 0, 0, 0, m_Width, m_Height, m_Format, GL_UNSIGNED_BYTE, data);

	}
}

